<?php
/**
 * Licensed under the MIT License
 *
 * Copyright (c) 2010 Alexandre Croiseaux
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */

if (isset($_POST["go"]))
{
	//echo "<pre>";
	//print_r($_POST);
	//echo "</pre>";

	$destFolderContainer = $_POST["destFolderContainer"];
	if ($destFolderContainer[strlen($destFolderContainer) - 1] == "/") $destFolderContainer = substr($destFolderContainer, 0, strlen($destFolderContainer) - 1);
	$destPackageName = $_POST["destPackageName"];
	$site_xml = $destFolderContainer."/apps/site/web/xml/config/site.xml";
	
	///////////////////////////////////////
	// create rep
	///////////////////////////////////////
	if (!is_dir($destFolderContainer))
	{
		if (!mkdir($destFolderContainer))
		{
			echo "Folder '".$destFolderContainer."' not found!";
			exit;
		}
	}

	///////////////////////////////////////
	// copy files
	///////////////////////////////////////
	$copy = copyr(".", $destFolderContainer);
	echo $copy ? "<br/>Copy OK<br/>" : "<br/>Copy KO<br/>";
	
	
	///////////////////////////////////////
	// rename proj file
	///////////////////////////////////////
	@rename($destFolderContainer."/marcel-as3-framework.as3proj", $destFolderContainer."/".array_pop(explode("/", $destFolderContainer)).".as3proj");
	@rename($destFolderContainer."/src/actionscript/project/project_name", $destFolderContainer."/src/actionscript/project/".$destPackageName);
	
	
	///////////////////////////////////////
	// create uis
	///////////////////////////////////////
	$imports = "";
	$classNames = "";
	$nodes = "";
	for ($i = 0; $i < 10; $i++)
	{
		$assets = "";
		$name = $_POST["ui_id_".$i];
		$fullQualifiedClassName = $destPackageName.".".$_POST["ui_class_".$i];
		
		if ($name != "name_ui")
		{
			$src_file = "src/actionscript/project/project_name/uis/content/PageUI.as";
			if (isset($_POST["ui_".$i."_form_cb"]) && $_POST["ui_".$i."_form_cb"])
			{
				$src_file = "src/actionscript/project/project_name/uis/content/FormUI.as";
				$assets = "assets=\"forms_xml\" ";
			}
			if (isset($_POST["ui_".$i."_video_cb"]) && $_POST["ui_".$i."_video_cb"]) $src_file = "src/actionscript/project/project_name/uis/content/VideoUI.as";
			
			$imports .= "import ".$fullQualifiedClassName.";\n\t";
			$nodes .= "\n\t\t<ui id=\"".$name."\" classname=\"".$fullQualifiedClassName."\" ".$assets."/>";
			
			$path = explode(".", $fullQualifiedClassName);
			@mkdir($destFolderContainer."/src/actionscript/project/".implode("/", array_slice($path, 0, count($path)-1)), 0777, true);
			$dest_file = $destFolderContainer."/src/actionscript/project/".implode("/", $path).".as";
			
			$classNames .= "\t\t".array_pop($path).";\n";
			
			echo "<br/>Creating UI '".$name."' (".$fullQualifiedClassName.")";
			copy($src_file, $dest_file);
			chmod($dest_file, 0777);
			updateUIFile($dest_file, $fullQualifiedClassName);
		}
	}
	
	// update Index.as
	$file = $destFolderContainer."/src/actionscript/project/".$destPackageName."/Index.as";
	$content = file_get_contents($file);
	$content = str_replace("import ".$destPackageName.".uis.content.*;", $imports, $content);
	$content = str_replace("PageUI; VideoUI; FormUI;", $classNames, $content);
	file_put_contents($file, $content);
	
	// update site.xml
	$content = file_get_contents($site_xml);
	$content = str_replace("</uis>", $nodes."\n\t</uis>", $content);
	file_put_contents($site_xml, $content);
	
	
	///////////////////////////////////////
	// create states
	///////////////////////////////////////
	echo "<br/><br/>";
	
	$nav_xml = "<navigation>\n\t<btns>\n\t\t<btn state=\"home\">State home</btn>\n";
	$nodes = "";
	for ($i = 0; $i < 10; $i++)
	{
		$name = $_POST["state_id_".$i];
		if ($name != "state")
		{
			$nodes .= "\n\t\t<state id=\"".$name."\" open_uis=\"".implode(",", $_POST["state_".$i."_cb"])."\" keep_uis=\"\" />";
			$nav_xml .= "\t\t<btn state=\"".$name."\">State ".$name."</btn>\n";
			echo "<br/>Creating State '".$name."' (".implode(",", $_POST["state_".$i."_cb"]).")";
		}
	}
	
	// update site.xml
	$content = file_get_contents($site_xml);
	$content = str_replace("</states>", $nodes."\n\t</states>", $content);
	file_put_contents($site_xml, $content);
	
	// update nav.xml
	$nav_xml .= "\n\t</btns>\n</navigation>";
	file_put_contents($destFolderContainer."/apps/site/web/xml/texts/fr/navigation.xml", $nav_xml);
	
	
	///////////////////////////////////////
	// remove FW default stuff
	///////////////////////////////////////
	/*
	unlink($destFolderContainer."/src/actionscript/project/".$destPackageName."/uis/content/FormUI.as");
	unlink($destFolderContainer."/src/actionscript/project/".$destPackageName."/uis/content/PageUI.as");
	unlink($destFolderContainer."/src/actionscript/project/".$destPackageName."/uis/content/PageUI.as");
	rmdir($destFolderContainer."/src/actionscript/project/".$destPackageName."/uis/content");
	*/
	$doc = new DomDocument();
	$doc->load($site_xml);
	for ($i = 0; $i < 4; $i++)
	{
		$doc->getElementsByTagName('uis')->item(0)->removeChild($doc->getElementsByTagName('ui')->item(3));
		$doc->getElementsByTagName('states')->item(0)->removeChild($doc->getElementsByTagName('state')->item(1));
	}
	$doc->save($site_xml);
	
	
	///////////////////////////////////////
	// done
	///////////////////////////////////////
	echo "<br/><br/>Project created!";
}

function parseFile($file)
{
	global $destPackageName;
	
	$startContent = file_get_contents($file);
	$content = str_replace("project_name", $destPackageName, $startContent);
	if ($content != $startContent)
	{
		file_put_contents($file, $content);
		echo "Updating file ".$file."<br>";
	}
}

function updateUIFile($file, $fullQualifiedClassName)
{
	$a = explode(".", $fullQualifiedClassName);
	$className = array_pop($a);
	$packageName = implode(".", $a);
	
	$content = file_get_contents($file);
	$content = str_replace("package project_name.uis.content", "package ".$packageName, $content);
	$content = str_replace("public class VideoUI", "public class ".$className, $content);
	$content = str_replace("public class FormUI", "public class ".$className, $content);
	$content = str_replace("public class PageUI", "public class ".$className, $content);
	$content = str_replace("project_name", array_shift($a), $content);
	file_put_contents($file, $content);
}

function copyr($source, $dest)
{
	// Simple copy for a file
	if (is_file($source))
	{
		$c = copy($source, $dest);
		chmod($dest, 0777);
		
		// Check .xml and .as files
		$ext = strrchr($dest, ".");
		if ($c && ($ext == ".as" || $ext == ".xml" || $ext == ".as3proj")) parseFile($dest);
		
		return $c;
	}
	// Make destination directory
	if (!is_dir($dest))
	{
		$oldumask = umask(0);
		mkdir($dest, 0777);
		umask($oldumask);
	}

	// Loop through the folder
	$dir = dir($source);
	$scriptName = array_pop(explode("/", $_SERVER["SCRIPT_NAME"]));
	while (false !== $entry = $dir->read())
	{
		if ($entry == "." || $entry == "content" || $entry == ".." || stristr($entry, ".svn") || stristr($entry, "_svn") || $entry == $scriptName)
		{
			continue;
		}
		
		// Deep copy directories
		if ($dest !== $source."/".$entry)
		{
			copyr($source."/".$entry, $dest."/".$entry);
		}
	}
	
	// Clean up
	$dir->close();
	return true;
}

?>


<html>
	
	<head>
		<script language="javascript">
			
			function updatePackageName()
			{
				for (var i = 0; i < 10; i++)
				{
					document.getElementById("span_" + i).innerHTML = document.getElementById("destPackageName").value + ".";
				}
			}
			
			function updateUIList()
			{
				var list = [];
				for (var i = 0; i < 10; i++)
				{
					var uiId = document.getElementById("ui_id_" + i).value;
					if (uiId != "name_ui") list.push(uiId);
				}
			
				for (i = 0; i < 10; i++)
				{
					var innerHtml = "";
					for (j = 0; j < list.length; j++)
					{
						var cbId = "state_" + i + "_cb_" + j;
						innerHtml += '<input type="checkbox" name="state_' + i + '_cb[]" id="' + cbId + '" value="' + list[j] + '" /><label for="' + cbId + '">' + list[j] + '</label>';
					}
					document.getElementById("state_id_uis_" + i).innerHTML = innerHtml;
				}
			}
			
		</script>
	</head>
	
	<body onload="updatePackageName();updateUIList();">
		<?php
		if (!isset($_POST["go"]))
		{
		?>
		<form action="" method="POST">
		New Project path: <input name="destFolderContainer" style="width:300px;" value="<?php echo str_replace('\\', '/', realpath('../')); ?>/client_YYYYMMDD_project">
		<br><br>
		Package name: <input id="destPackageName" name="destPackageName" value="clientproj" onkeyup="updatePackageName();">
		<br><br>
			
		UIs :
		<br>
		<?php
		for ($i = 0; $i < 10; $i++) {
		?>
		<input id="ui_id_<?php echo $i;?>" name="ui_id_<?php echo $i;?>" value="name_ui" onkeyup="updateUIList();">
		<span id="span_<?php echo $i;?>">clientproj.</span><input name="ui_class_<?php echo $i;?>" value="uis.UI">
		<input type="checkbox" name="ui_<?php echo $i;?>_form_cb" id="ui_<?php echo $i;?>_form_cb" /><label for="ui_<?php echo $i;?>_form_cb"> contains form</label>
		<input type="checkbox" name="ui_<?php echo $i;?>_video_cb" id="ui_<?php echo $i;?>_video_cb" /><label for="ui_<?php echo $i;?>_video_cb"> contains video</label>
		<br/>
		<?php
		}
		?>
		
		<br>
			
		States :
		<br>
		<?php
		for ($i = 0; $i < 10; $i++) {
		?>
		<input name="state_id_<?php echo $i;?>" value="state">
		<span id="state_id_uis_<?php echo $i;?>"></span>
		<br/>
		<?php
		}
		?>
		
		<br><br>
		<input type="hidden" name="go" value="ok">
		<input type="submit" value="Go go go !">
		</form>
		<?php
		}
		?>
	</body>
</html>